<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-button type="primary"
                 @click="showDialog">添加分类</el-button>
      <!-- 列表区 -->

      <tree-table ref="table"
                  sum-text="sum"
                  index-text="#"
                  :data="categoryList"
                  :columns="columns"
                  :selection-type="false"
                  :expand-type="false"
                  border
                  show-row-hover
                  show-index
                  tree-type
                  is-fold>
        <template slot="isok"
                  slot-scope="scope">
          <i class="el-icon-success"
             style="color:lightgreen"
             v-if="scope.row.cat_deleted === true"></i>
          <i class="el-icon-error"
             style="color:lightgreen"
             v-else-if="scope.row.cat_deleted === false"></i>
        </template>
        <template slot="level"
                  slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0 ">一级</el-tag>
          <el-tag type="success"
                  v-else-if="scope.row.cat_level === 1 ">二级</el-tag>
          <el-tag type="warning"
                  v-else>三级</el-tag>
        </template>
        <template slot="operate">
          <el-button type="warning"
                     round>编辑</el-button>
          <el-button type="danger "
                     round>删除</el-button>
        </template>
      </tree-table>

      <!-- 分页区 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pageInfo.currentPage"
                     :page-sizes="pageInfo.pageSizes"
                     :page-size="pageInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="pageInfo.totalRecord">
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类"
               :visible.sync="addCategoryDialogVisible"
               @click="closeAddCategoryDialog">
      <el-form :model="addCategoryForm"
               :rules="categoryRules"
               label-width="100px"
               ref="addCategoryRef">
        <el-form-item label="分类名称"
                      prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类"
                     >
          <el-cascader v-model="parentSelectArray"
                       :options="parentCategoryList"
                       :props="props" clearable size="mini" change-on-select
                       @change="changeParentCategory"></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="closeAddCategoryDialog">取 消</el-button>
        <el-button type="primary"
                   @click="submitCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 分类名称的校验规则
    var checkCategoryName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('分类名称不能为空'))
      }
      callback()
    }
    return {
      // 分类数组
      categoryList: [],
      // 查询分类的参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 分页相关参数
      pageInfo: {
        currentPage: 1,
        pageSizes: [5, 10, 15, 20],
        pageSize: 5,
        totalRecord: 0
      },
      // 第三方组件的树形插件
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template', // 标识将当前列定义为模板列
          template: 'isok' // 标识当前这一列使用模板名称
        },
        {
          label: '级别',
          type: 'template', // 标识将当前列定义为模板列
          template: 'level' // 标识当前这一列使用模板名称
        },
        {
          label: '操作',
          type: 'template', // 标识将当前列定义为模板列
          template: 'operate' // 标识当前这一列使用模板名称
        }
      ],
      // 控制添加分类的对话框显示或者隐藏
      addCategoryDialogVisible: false,
      // 添加分类的表单
      addCategoryForm: {},
      categoryRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 50, message: '字符在1-50之间', trigger: 'blur' },
          { validator: checkCategoryName, trigger: 'blur' }
        ]
      },
      // 父级分类对象数组，又来在添加分类的时候使用
      parentCategoryList: [],
      // 级联选择器的配置项
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
        // checkStrictly: true
      },
      // 级联选择器选中的双向绑定数组
      parentSelectArray: []
    }
  },
  created () {
    this.getCategoryList()
  },
  methods: {
    // pageSize选择周触发该函数
    handleSizeChange (val) {
      this.pageInfo.pageSize = val
      this.queryInfo.pagesize = val
      this.getCategoryList()
    },
    // 跳转的时候触发该事件
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getCategoryList()
    },
    async getCategoryList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取分类列表失败')
        return
      }
      this.categoryList = res.data.result
      // 赋予分页的参数
      this.pageInfo.currentPage = res.data.pagenum === 0 ? 1 : res.data.pagenum
      this.pageInfo.totalRecord = res.data.total
      this.pageInfo.pageSize = res.data.pagesize
    },
    // 调出添加分类的对话框
    showDialog () {
      this.getParentCategory()
      this.addCategoryDialogVisible = true
    },
    async getParentCategory () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2, pagenum: 1, pagesize: 10 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父类分类列表失败')
      }
      this.parentCategoryList = res.data.result
    },
    changeParentCategory () {
    },
    submitCategory () {
      // 由于分类可能是一级、二级、三级，都是由父类选择器所决定的，这时候需要做判断
      if (this.parentSelectArray.length > 0) {
        // 说明有选择父类
        // 将数组中最后一个元素作为分类的父级元素，将其等级设置为数组的长度
        this.addCategoryForm.cat_pid = this.parentSelectArray[this.parentSelectArray.length - 1]
        this.addCategoryForm.cat_level = this.parentSelectArray.length
      } else {
        // 没有选择父级分类，则将该分类作为一级分类
        this.addCategoryForm.cat_pid = 0
        this.addCategoryForm.cat_level = 0
      }
      // 校验表单是否合法
      this.$refs.addCategoryRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('categories', this.addCategoryForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getCategoryList()
        this.addCategoryDialogVisible = false
      })
    },
    closeAddCategoryDialog () {
      this.$refs.addCategoryRef.resetFields()
      this.parentSelectArray = []
      this.addCategoryForm = {}
      this.addCategoryDialogVisible = false
    }
  }
}
</script>

<style>
.el-cascader {
    width: 100%;
    /* height: 200px; */
}
</style>
